package com.lorenzogao.controller

import com.lorenzogao.repository.GirlRepository
import com.lorenzogao.service.GirlService
import com.lorenzogao.domian.Gril
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.*
import java.math.BigInteger
import javax.validation.Valid

/**
 * Created by 15270 on 2018/1/23.
 */

@RestController
class GrilController {

    @Autowired
    private lateinit var girlRepository: GirlRepository

    @Autowired
    private lateinit var girlService: GirlService

    /**
     *  查询所有数据列表
     */
    @GetMapping(value = "/girls")
    fun girlList(): List<Gril> {
        return girlRepository.findAll()
    }


    /**
     * 添加数据
     */
    @PostMapping(value = "/girls")
    fun addGirl(@Valid girl: Gril, bingResult: BindingResult): Gril? {
        if (bingResult.hasErrors()) {
            System.out.print(bingResult.fieldError.defaultMessage)
            return null
        }

        return girlRepository.save(girl)

    }


    /**
     * 跟据id查询数据
     */
    @GetMapping(value = "/girls/{id}")
    fun queryGirld(@PathVariable("id") id: Int): Gril? {
        try {
            return girlRepository.findOne(id)
        } catch (e: Exception) {

        }
        return null
    }


    /**
     * 更新
     */
    @PutMapping(value = "/girls/{id}")
    fun update(@PathVariable("id") id: Int,
               @RequestParam("cupSize") cupSize: String,
               @RequestParam("age") age: Int,
               @RequestParam("monery") monery: Int): Gril {

        val gril = Gril(cupSize, age, monery,id)
        return girlRepository.save(gril)
    }

    /**
     * 删除
     */

    @DeleteMapping(value = "/girls/{id}")
    fun grilDelete(@PathVariable("id") id: Int) {

        girlRepository.delete(id)
    }


    /**
     * 通过年龄查询
     *
     */

    @GetMapping(value = "/girls/age/{age}")
    fun girlListByAge(@PathVariable("age") age: Int): List<Gril> {
        return girlRepository.findByAge(age)
    }


    @PostMapping(value = "girls/two")
    fun girlTwo() {
        girlService.insertTwo()
    }

}